<!-- PHP Controller script used in conjunction with maindb.html.php
to execute a MySQL script -->

<?php
$sqlFileToExecute = $_REQUEST['sqlFileToExecute'].'.sql';
$hostName = $_REQUEST['hostName'];
$dbUser = $_REQUEST['dbUser'];
$dbPassWord = $_REQUEST['dbPassWord'];
$adminPassWord = $_REQUEST['adminPassWord'];

echo 'Script to execute: '.$sqlFileToExecute.'<br>';
echo 'Host Name: '.$hostName.'<br>';
echo 'Database User Name: '.$dbUser.'<br>';
// echo 'Database User Password: '.$dbPassWord.'<br>'.'<br>';

$adminPWVerify = 'admin';

if ($adminPassWord != $adminPWVerify) {
	die ("You are not allowed to execute this script");
	}

$command = "mysqldump --host=$hostName --user=$dbUser --password=$dbPassWord repomath>repomath_backup.sql";
system($command);

// Restore the database: create the database at the mysql prompt
// At the mysql prompt: --u [user] --p [password] dbName<repomath_backup.sql 

$link = mysqli_connect($hostName, $dbUser, $dbPassWord);
if (!$link) {
	
	die ('MySQL Connection error: ' . mysqli_connect_error($link));
	}

$f = fopen($sqlFileToExecute,"r");
if (!$f) {
	die ('Could not open file');
	}
	
$sqlFile = fread($f, filesize($sqlFileToExecute));
if (!$sqlFile) {
	die ('Could not read the file');
	}
	
$sqlArray = explode(';',$sqlFile);

foreach ($sqlArray as $stmt) {
	
	$result = mysqli_query($link,$stmt);
	if (mysqli_error($link)) {
		die (mysqli_error($link));
	}
	
}
echo "Script is executed succesfully!"; 
?>